package org.walklink.core.plugins;

import org.assertj.core.util.Lists;
import org.springframework.core.Ordered;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * 默认插件管理器
 *
 * @author lidishan
 */
public class DefaultPluginManager {

    /**
     * 加载第一个插件（ordered最小的那个优先级最高）
     * @param clazz class
     * @param <S> 泛型
     * @return 实例对象
     */
    public static <S extends Ordered> S loadPrimary(Class<S> clazz) {
        List<S> candidates = loadAllOrdered(clazz);
        return candidates.get(0);
    }

    public static <S extends Ordered> List<S> loadAllOrdered(Class<S> clazz) {
        Iterator<S> iterator = loadAll(clazz);

        if (!iterator.hasNext()) {
            throw new IllegalStateException(String.format(
                    "No implementation defined in /META-INF/services/%s, please check!", clazz.getName()));
        }
        // 获取迭代中的所有SPI实现实例,然后进行排序，取优先级最高的那个
        List<S> candidates = Lists.newArrayList(iterator);
        candidates.sort(Comparator.comparingInt(Ordered::getOrder));

        return candidates;
    }

    public static <S> Iterator<S> loadAll(Class<S> clazz) {
        ServiceLoader<S> loader = ServiceLoader.load(clazz);

        return loader.iterator();
    }


}
